<template>
  <div class="app-container">
    <div
      class="header"
      style="display: flex; justify-content: space-between"
    >
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item>
          <el-button
            icon="refresh"
            color=" rgb(69, 76, 105)"
            style="color: #fff"
            @click="resetQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleAdd"
            v-hasPermi="['system:car:add']"
            style="padding: 0 20px"
          >
            新 增
          </el-button>
        </el-form-item>
      </el-form>
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item
          label=""
          prop="couponName"
        >
          <el-input
            v-model="queryParams.couponName"
            placeholder="请输入优惠券名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item
          label=""
          prop="type"
        >
          <el-select
            v-model="queryParams.type"
            placeholder="请选择优惠券类型"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="(item, index) in allType"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label=""
          prop="state"
        >
          <el-select
            v-model="queryParams.state"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="(item, index) in allState"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="info"
            icon="Search"
            @click="handleQuery()"
          />
        </el-form-item>
      </el-form>
    </div>

    <el-table
      v-loading="loading"
      :data="couponList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="优惠券名称"
        align="center"
        prop="couponName"
      />
      <el-table-column
        label="优惠券类型"
        align="center"
        prop="type"
      >
        <template #default="scope">
          <span v-if="scope.row.type === '0'">通用打折券</span>
          <span v-if="scope.row.type === '1'">顺风车打折券</span>
          <span v-if="scope.row.type === '2'">成际打折券</span>
        </template>
      </el-table-column>
      <el-table-column
        label="优惠券面值"
        align="center"
        prop="couponAmount"
      />
      <el-table-column
        label="最低消费"
        align="center"
        prop="lowestConsume"
      />
      <el-table-column
        label="有效期限"
        align="center"
        prop="availableDate"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.availableDate, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="state"
      >
        <template #default="scope">
          {{ allState.find((item) => item.value == scope.row.state).label }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"

      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handlePublish(scope.row)"
            v-hasPermi="['system:coupon:edit']"
            >发布</el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:coupon:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:coupon:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>




    <!-- 发布 的弹窗组件 -->
    <el-dialog
      :title="title"
      v-model="pulltan"
      width="500px"
      append-to-body
    >
      <div style="font-size: 18px; font-weight: bold; margin-bottom: 20px; margin-left: 20px;">
        发布
      </div>
      <el-form
        ref="couponRef"
        :model="pulldata"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          label="优惠券名称"
          prop="couponName"
        >
          <el-input
            v-model="data.pulldata.couponName"
            placeholder="请输入优惠券名称"
          />
        </el-form-item>
        <el-form-item
          label="领取开启时间"
          prop="startTime"
        >
            <el-date-picker
              v-model="data.pulldata.startTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择领取开启时间"
            />
        </el-form-item>
        <el-form-item
          label="领取结束时间"
          prop="endTime"
        >
            <el-date-picker
              v-model="data.pulldata.endTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择领取截止时间"
            />
        </el-form-item>
        <el-form-item
          label="发布数量"
          prop="publishNum"
        >
          <el-input
            v-model="data.pulldata.publishNum"
            placeholder="请输入发布数量，-1表示不限量"
          />
        </el-form-item>
        <!-- radio就是选中的label值 -->
        <div>
          <text style="font-weight: bold; margin-left: 20px;">是否不数量</text>
          <el-radio v-model="radio" label="-1" class="xiangou">不限量</el-radio>
          <el-radio v-model="radio" label="0">限量</el-radio>
        </div>
        <el-form-item
          label="状态"
          prop="state"
        >
          <el-radio-group v-model="data.pulldata.state">
            <el-radio label="0">开启</el-radio>
            <el-radio label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="pullsubmitForm"
            >确 定 发 布</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 编辑的优惠券对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="couponRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          label="优惠券名称"
          prop="couponName"
        >
          <el-input
            v-model="form.couponName"
            placeholder="请输入优惠券名称"
          />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="form.type">
          <el-select v-model="form.type" placeholder="请选择优惠券类型" >
            <el-option
              v-for="item in allType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
<!--          <span>{{ selectedTypeLabel }}</span>-->
        </el-form-item>

        <el-form-item
          label="优惠券面值"
          prop="couponAmount"
        >
          <el-input
            v-model="form.couponAmount"
            placeholder="请输入优惠券面值"
          />
        </el-form-item>
        <el-form-item
          label="最低消费"
          prop="lowestConsume"
        >
          <el-input
            v-model="form.lowestConsume"
            placeholder="请输入最低消费"
          />
        </el-form-item>
        <el-form-item
          label="有效期限"
          prop="availableDate"
        >
          <el-date-picker
            clearable
            v-model="form.availableDate"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期限"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="状态"
          prop="state"
        >
          <el-radio-group v-model="form.state">
            <el-radio label="0">开启</el-radio>
            <el-radio label="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Coupon">
import {
  listCoupon,
  getCoupon,
  delCoupon,
  addCoupon,
  updateCoupon,
  pullscoupon,
} from "@/api/system/coupon";
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();

const couponList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const radio = ref('-1')
//加入的
//开启或关闭
const ison = ref('0')
// const pulldata = ref([
//       {
//         couponId:'',
//         startTime:'',
//         couponName:'',
//         endTime:'',
//         publishNum:'',
//         state:0
//       }
// ])
//加入的
const pulltan = ref(false);
const data = reactive({
  allState: [
    {
      label: "关闭",
      value: 1,
    },
    {
      label: "开启",
      value: 0,
    },
  ],
  allType: [
    {
      label: "通用打折券",
      value: '0',
    },
    {
      label: "顺风车打折券",
      value: '1',
    },
    {
      label: "成际打折券",
      value: '2',
    },
  ],
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    couponName: null,
    type: null,
    state: null,
  },
  rules: {
    state: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  },


  // //加入的，存储发布数据
  pulldata: {
    couponId:'',
    startTime:'',
    couponName:'',
    endTime:'',
    publishNum:'',
    state:'0',
  },
});

const { queryParams, form, rules, allState, allType } = toRefs(data);

/** 查询优惠券列表 */
function getList() {
  loading.value = true;
  listCoupon(queryParams.value).then((response) => {
    console.log(response,'resposeggggggggggggggggyyyyyyyy');
    couponList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  pulltan.value = false;
  reset();
}


// 表单重置
function reset() {
  form.value = {
    couponId: null,
    couponName: null,
    type: null,
    couponAmount: null,
    lowestConsume: null,
    availableDate: null,
    state: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("couponRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.couponId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加优惠券";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = row;
  open.value = true;
  // 根据type值匹配对应的文字描述
  const typeOption = allType.value.find(item => item.value === row.type);
  if (typeOption) {
    form.value.type = typeOption.label;
  }
  title.value = "修改优惠券";
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponRef"].validate((valid) => {
    if (valid) {
      if (form.value.couponId != null) {
        updateCoupon(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCoupon(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}



/** 删除按钮操作 */
function handleDelete(row) {
  const couponIds = row.couponId || ids.value;
  proxy.$modal
    .confirm('是否确认删除优惠券编号为"' + couponIds + '"的数据项？')
    .then(function () {
      return delCoupon(couponIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/coupon/export",
    {
      ...queryParams.value,
    },
    `coupon_${new Date().getTime()}.xlsx`
  );
}


//加入发布提交的按钮
function pullsubmitForm(){

    data.pulldata.publishNum = data.pulldata.publishNum - 0

    if(radio.value == '-1'){
       data.pulldata.publishNum = -1
    }
    //把状态也传进去
    data.pulldata.state = ison.value


    pullscoupon(data.pulldata).then(response=>{
        proxy.$modal.msgSuccess("发布成功")
    })
  //关闭弹窗
  pulltan.value = false
}

//发布优惠券
function handlePublish(row){
  //点击发布弹出发布会话框
  pulltan.value = true
  data.pulldata.couponId = row.couponId
  data.pulldata.couponName = row.couponName
  data.pulldata.endTime = row.availableDate
  data.pulldata.startTime = row.createTime
  data.pulldata.state = row.state
}

getList();

// onMounted(() => {
//   console.log("coupon mounted",couponList);
// });

// 在 script 部分添加一个计算属性
const selectedTypeLabel = computed(() => {
  const option = allType.value.find(item => item.value === form.value.type);
  return option? option.label : '';
});
</script>


<style scoped lang="scss">
    .xiangou{
      margin-left: 30px;
    }

    .off{
      margin-left: 15px;
    }
</style>
